<template>
  <div class="audit-goods-list">
    <!-- 列表头部 -->
    <div class="list-header">
      <h3>{{ getStatusTitle() }}</h3>
      <el-button type="primary" @click="refreshList" :loading="loading">
        <i class="el-icon-refresh"></i>
        刷新
      </el-button>
    </div>

    <!-- 商品列表 -->
    <div v-if="!loading && goodsList.length > 0">
      <el-table
        :data="goodsList"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f5f5', color: '#333' }"
      >
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->

        <el-table-column label="商品图片" min-width="100">
          <template #default="{ row }">
            <el-image
              :src="row.mainImage"
              :alt="row.goodsName"
              style="width: 60px; height: 60px"
              fit="cover"
              @error="handleImageError"
            />
          </template>
        </el-table-column>

        <el-table-column prop="goodsName" label="商品名称" min-width="180">
          <template #default="{ row }">
            <div class="goods-name">{{ row.goodsName }}</div>
            <!-- <div class="goods-category">{{ getCategoryName(row.categoryId) }}</div> -->
          </template>
        </el-table-column>

        <el-table-column prop="price" label="价格" min-width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="stock" label="库存" min-width="80" />

        <el-table-column prop="auditStatus" label="审核状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusType(row.auditStatus)" size="small">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>



        <el-table-column prop="createTime" label="发布时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column 
          label="操作" 
          min-width="120" 
          fixed="right"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="viewDetail(row)">
                查看详情
              </el-button>



              <el-button
                v-if="status === 'rejected'"
                type="success"
                size="small"
                @click="rePublish(row)"
              >
                重新发布
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-else-if="!loading && goodsList.length === 0"
      :description="getEmptyDescription()"
    />

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 商品详情对话框 -->
    <el-dialog
      :visible.sync="detailVisible"
      title="商品详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentGoods" class="goods-detail">
        <div class="detail-images">
          <el-carousel
            v-if="getDisplayImages(currentGoods).length > 0"
            height="300px"
          >
            <el-carousel-item
              v-for="(image, index) in getDisplayImages(currentGoods)"
              :key="index"
            >
              <el-image
                :src="image"
                style="width: 100%; height: 100%"
                fit="cover"
              />
            </el-carousel-item>
          </el-carousel>
          <div v-else class="no-image">
            <el-image
              :src="currentGoods.mainImage"
              style="width: 100%; height: 100%"
              fit="cover"
            />
          </div>
        </div>

        <div class="detail-info">
          <h4>{{ currentGoods.goodsName }}</h4>
          <!-- <p class="category">
            分类：{{ getCategoryName(currentGoods.categoryId) }}
          </p> -->
          <p class="price">价格：¥{{ currentGoods.price }}</p>
          <p class="original-price">原价：¥{{ currentGoods.originalPrice }}</p>
          <p class="stock">库存：{{ currentGoods.stock }}</p>
          <p class="audit-status">
            审核状态：
            <el-tag
              :type="getAuditStatusType(currentGoods.auditStatus)"
              size="small"
            >
              {{ getAuditStatusText(currentGoods.auditStatus) }}
            </el-tag>
          </p>
          
          <p class="description">描述：{{ currentGoods.description }}</p>

          <!-- 审核信息 -->
          <div v-if="currentGoods.auditorName" class="audit-info">
            <p class="auditor">审核人：{{ currentGoods.auditorName }}</p>
            <p class="audit-time">
              审核时间：{{ formatDate(currentGoods.auditTime) }}
            </p>
            <p v-if="currentGoods.auditRemark" class="audit-remark">
              审核备注：{{ currentGoods.auditRemark }}
            </p>
          </div>

          <!-- 审核失败原因 -->
          <div
            v-if="status === 'rejected' && currentGoods.rejectReason"
            class="reject-reason"
          >
            <p class="reason-title">拒绝原因：</p>
            <p class="reason-content">{{ currentGoods.rejectReason }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/utils/axios";

export default {
  name: "AuditGoodsList",
  props: {
    status: {
      type: String,
      required: true,
      validator: value => ["pending", "approved", "rejected"].includes(value)
    }
  },
  data() {
    return {
      goodsList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      detailVisible: false,
      currentGoods: null
    };
  },
  watch: {
    status: {
      handler() {
        this.loadGoodsList();
      },
      immediate: true
    }
  },
  methods: {
    // 获取状态标题
    getStatusTitle() {
      const titleMap = {
        pending: "待审核商品",
        approved: "审核通过商品",
        rejected: "审核失败商品"
      };
      return titleMap[this.status] || "商品列表";
    },

    // 获取空状态描述
    getEmptyDescription() {
      const descMap = {
        pending: "暂无待审核商品",
        approved: "暂无审核通过商品",
        rejected: "暂无审核失败商品"
      };
      return descMap[this.status] || "暂无商品";
    },

    // 加载商品列表
    async loadGoodsList() {
      try {
        this.loading = true;
        
        // 获取当前用户ID
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
        const userId = userInfo.userId || this.$store.state.user.userId;
        
        if (!userId) {
          this.$message.error('用户信息获取失败，请重新登录');
          return;
        }
        
        const urlMap = {
          pending: "/goods/user/audit/pending",
          approved: "/goods/user/audit/approved",
          rejected: "/goods/user/audit/rejected"
        };

        const url = urlMap[this.status];
        if (!url) {
          this.$message.error("无效的状态类型");
          return;
        }

        const response = await axios.get(url, {
          params: {
            userId: userId,
            current: this.currentPage,
            size: this.pageSize
          }
        });

        if (response.data.success) {
          this.goodsList = response.data.data.records || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.message || "获取商品列表失败");
        }
      } catch (error) {
        console.error("获取商品列表失败:", error);
        this.$message.error("获取商品列表失败");
      } finally {
        this.loading = false;
      }
    },

    // 刷新列表
    refreshList() {
      this.loadGoodsList();
    },

    // 查看详情
    viewDetail(goods) {
      console.log("查看详情被调用:", goods);
      this.currentGoods = goods;
      this.detailVisible = true;
      console.log("detailVisible:", this.detailVisible);
    },

    // 关闭详情对话框
    handleCloseDetail() {
      this.detailVisible = false;
      this.currentGoods = null;
    },

    // 重新发布
    rePublish(goods) {
      this.$confirm("确定要重新发布这个商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message.success("切换到发布商品页面");
          // 通知父组件切换到发布商品标签页
          this.$emit('switch-to-publish');
        })
        .catch(() => {
          // 用户取消
        });
    },



    // 获取分类名称
    getCategoryName(categoryId) {
      const categoryMap = {
        1: "图书",
        2: "服装",
        3: "食品",
        4: "家居",
        5: "电子产品",
        6: "美妆",
        7: "运动",
        8: "母婴",
        9: "数码",
        10: "文具"
      };
      return categoryMap[categoryId] || "未知分类";
    },

    // 获取审核状态类型
    getAuditStatusType(auditStatus) {
      const statusMap = {
        0: "warning", // 待审核
        1: "success", // 审核通过
        2: "danger" // 审核拒绝
      };
      return statusMap[auditStatus] || "info";
    },

    // 获取审核状态文本
    getAuditStatusText(auditStatus) {
      const statusMap = {
        0: "待审核",
        1: "已通过",
        2: "已拒绝"
      };
      return statusMap[auditStatus] || "未知状态";
    },


    // 解析图片数组
    parseImages(imagesStr) {
      if (!imagesStr || imagesStr === "null") return [];
      try {
        return JSON.parse(imagesStr);
      } catch (error) {
        console.error("解析图片数组失败:", error);
        return [];
      }
    },

    // 获取要显示的图片列表
    getDisplayImages(goods) {
      const images = this.parseImages(goods.images);
      const displayImages = [];
      
      // 首先添加主图
      if (goods.mainImage) {
        displayImages.push(goods.mainImage);
      }
      
      // 然后添加其他图片
      if (images && images.length > 0) {
        displayImages.push(...images);
      }
      
      return displayImages;
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "-";
      const date = new Date(dateString);
      return date.toLocaleString("zh-CN");
    },

    // 处理图片加载错误
    handleImageError(event) {

    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadGoodsList();
    },

    // 当前页改变
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadGoodsList();
    }
  }
};
</script>

<style scoped>
.audit-goods-list {
  padding: 0;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid #e4e7ed;
}

.list-header h3 {
  color: #00caa8;
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.goods-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  font-size: 14px;
}

.goods-category {
  color: #666;
  font-size: 12px;
}

.price {
  color: #e74c3c;
  font-weight: 600;
  font-size: 16px;
}

.loading-container {
  padding: 40px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px 0;
}

.goods-detail {
  padding: 20px 0;
}

.detail-images {
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
}

.no-image {
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 10px;
}

.no-image .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.detail-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.detail-info p {
  margin: 8px 0;
  color: #666;
  line-height: 1.5;
}

.detail-info .price {
  color: #e74c3c;
  font-weight: 600;
}

.detail-info .original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.audit-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 10px;
}

.audit-info p {
  margin: 5px 0;
  color: #666;
}

.audit-info .auditor {
  font-weight: 600;
  color: #00caa8;
}

.reject-reason {
  margin-top: 15px;
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 10px;
}

.reason-title {
  font-weight: 600;
  color: #f56c6c;
  margin: 0 0 8px 0;
}

.reason-content {
  color: #666;
  margin: 0;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-start;
}

.action-buttons .el-button {
  width: 60%;
  margin: 0;
  border-radius: 8px;
}

/deep/ .el-pagination .el-pager li.is-active {
  background-color: #00caa8;
  color: white;
  border-radius: 8px;
}

/deep/ .el-button--primary {
  background-color: #00caa8;
  border-color: #00caa8;
  border-radius: 8px;
}

/deep/ .el-button--primary:hover {
  background-color: #00b894;
  border-color: #00b894;
}

/deep/ .el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
  border-radius: 8px;
}

/deep/ .el-carousel__item {
  display: flex;
  justify-content: center;
  align-items: center;
}

/deep/ .el-table {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0px 2px 10px 1px #0000002a;
}

/deep/ .el-table th {
  background-color: #f8f9fa !important;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

/deep/ .el-table td {
  border-bottom: 1px solid #f0f0f0;
}

/deep/ .el-table--border {
  border: 1px solid #e4e7ed;
}

/deep/ .el-tag {
  border-radius: 6px;
}

/deep/ .el-image {
  border-radius: 8px;
}
</style>
